<?php
/**
 * Created by PhpStorm.
 * User: My
 * Date: 2018/4/22
 * Time: 21:57
 */

namespace SRjgcWechat\jssdk;

use SRjgcWechat\accessToken\AccessToken;
use SRjgcWechat\curl\Curl;

class Jssdk{

    //https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
    const jssdk_getticket='https://api.weixin.qq.com/cgi-bin/ticket/getticket';
    private $config;
    public function __construct($config)
    {
        $this->config=$config;

    }

    public function getWxAccessToken(){

    }


    public function getJsApiToken(){

        if (!empty($_COOKIE['jssdk_ticket'])){
            return $_COOKIE['jssdk_ticket'];
        }
        else{
            $accessToken=new AccessToken($this->config);
            //https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
            $param=[
                'access_token'=>$accessToken->getAccessToken(),
                'type'=>'jsapi',
            ];

            $res=Curl::http(self::jssdk_getticket,$param,'','GET');
            $getticket=json_decode($res,true);

            setcookie('jssdk_ticket',$getticket['ticket'],time()+7000);

            return $getticket['ticket'];
        }

    }


    /**
     * 获取随机码
     */
    public function getRandCode($num=16){
        $array=array(
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','U','W','X','Y','Z',
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','u','w','x','y','z',
            '1','2','3','4','5','6','7','8','9','0'
        );

        $temstr='';
        $max=count($array);
        for ($i=1;$i<=$num;$i++){
            $key=rand(0,$max-1);
            $temstr.=$array[$key];
        }
        return $temstr;
    }


    public function shareWx(){
        //1.获取jsapi_token票据
        $jsApiToken=$this->getJsApiToken();

        $timestamp=time(); // 必填，生成签名的时间戳
        $nonceStr= $this->getRandCode(); // 必填，生成签名的随机串

        $url='http://webapp.lz4746.com/jssdk.php';
        $str='jsapi_ticket='.$jsApiToken.'noncestr='.$nonceStr. 'timestamp='.$timestamp.'url='.$url;
        $signature= sha1($str);// 必填，签名

        return $data=[
            'timestamp'=>$timestamp,
            'nonceStr'=>$nonceStr,
            'signature'=>$signature
        ];
    }
}